#!/usr/bin/env node

const greeting = 'Hello, World!';
const { extractSection } = require('./utils/exctract-dom') // 解析为使用class的pug文件
const { extractProject } = require('./utils/exctract-project') // 解析为使用class的pug文件
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');

function createTemplFolder(fullPath) {
  // 创建目录
  fs.mkdir(fullPath, { recursive: true }, (err) => {
    if (err) {
      return console.error(`创建目录时出错: ${err.message}`);
    }
    console.log(`[${fullPath}]创建成功！开始下载页面...`);
  });

}

async function fatchSvg(params) {
  const { url, name, folder } = params
  if (!url) { return false }
  const sampleFolder = path.join(__dirname, `../${folder}`, name);
  createTemplFolder(sampleFolder)
  // 启动浏览器
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(url, { waitUntil: 'networkidle2' });

  // 获取页面的 HTML 内容
  await page.waitForSelector('#page-content');
  const htmlContent = await page.content();
  // 保存 HTML 到本地 index.html 文件
  // fs.writeFileSync(`${sampleFolder}/index.html`, htmlContent, 'utf8');
  if (folder === 'projects') {
    extractProject(htmlContent, params)
  } else {
    extractSection(htmlContent, params)
  }
  await browser.close(); // 关闭浏览器
  return true
};


module.exports = fatchSvg;
